<template>
  <div class="app-container">
    <section>
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="formInline" label-width="150px">
          <el-form-item>
            <el-button type="primary" @click.prevent="handleHistory">历史列表</el-button>
          </el-form-item>
          <!--<span style="font-size:20px;font-weight: bold; display:block;margin-bottom: 20px;text-align: center;">采购订货单</span>-->
          <div>
            <el-form-item label="采购单号:">
              <el-input
                v-model="formInline.ordervoucher"
                placeholder="采购单号"
                onkeyup="value=value.replace(/[^\d]/g,'')"
              ></el-input>
            </el-form-item>
            <el-form-item label="采购人:">
              <el-input v-model="formInline.buyer" placeholder="采购人"></el-input>
            </el-form-item>
            <el-form-item label="供货商名称:">
              <!--<el-input v-model="formInline.BranchName" placeholder="购货单位"></el-input>-->
              <el-select
                v-model="formInline.SupplierId"
                filterable
                placeholder="供货商名称"
                @change="getSupplierID"
              >
                <el-option
                  v-for="item in SupplierList"
                  :key="item.SupplierId"
                  :label="item.SupplierName"
                  :value="item.SupplierId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供货商电话号码:">
              <el-input
                v-model="formInline.suppliermoblie"
                placeholder="电话号码"
                maxlength="11"
                onkeyup="value=value.replace(/[^\d]/g,'')"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>
      </el-col>
      <el-table
        :data="skulist"
        v-loading="skulistLoading"
        ref="multipleTable"
        border
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="ProductId" label="商品ID" align="center"></el-table-column>
        <el-table-column prop="SKUName" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="SKUUnitNo" label="单位" align="center"></el-table-column>
        <el-table-column prop="g" label="规格" align="center"></el-table-column>
        <el-table-column prop="SKUSalePrice" sortable label="实价" align="center"></el-table-column>
        <el-table-column prop="OrderNum" sortable label="订货数量" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.OrderNum" :min="1" size="mini"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="TaxRate" sortable label="税率" align="center"></el-table-column>
        <el-table-column prop="Description" sortable label="备注" align="center">
          <template slot-scope="scope">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="scope.row.Description"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="Sum" sortable label="合计" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.OrderNum * scope.row.SKUSalePrice}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          background
          layout=" prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
          style="float:right ;margin-top: 10px;"
        ></el-pagination>
      </div>
      <div style="margin-top: 20px">
        <el-button @click="toggleSelection(skulist)">全选</el-button>
        <el-button @click="toggleSelection()">取消选择</el-button>
        <el-button type="primary" @click.native="OderVisible = true">订货</el-button>
      </div>

      <el-dialog title="提示" :visible.sync="OderVisible" width="30%">
        <span>是否确认订货</span>
        <span slot="footer">
          <el-button @click="OderVisible = false">取 消</el-button>
          <el-button type="primary" @click.native="addSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </section>
  </div>
</template>

<script>
import { SKUList, GetAnySupplierList, PurchaseOrder } from "@/api/api";
import Config from "../../api/config";
export default {
  data() {
    return {
      skulistLoading:false,
      jsonspr: [],
      SupplierList: [],
      OderVisible: false,
      lookFormVisible: false,
      lookLoading: false,
      logisticsLoading: false,
      logisticsFormVisible: false,
      addLoading: false,
      addFormVisible: false,
      skulist: [],
      page: 1,
      pageSize: 200000,
      total: 0,
      multipleSelection: [],
      addForm: {},
      logisticsForm: {},
      formInline: {
        SupplierId: "",
        suppliermoblie: "",
        suppliermoblie: "",
        ordervoucher: "",
        buyer: "",
        PurchaseDate: "",
        OderStatus: "",
        SKUId: 0,
        SKUName: ""
      }
    };
  },
  created() {
    this.getSkuList();
    this.GetAnySupplierList();
  },

  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        console.log(column);
        console.log(index);
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        if (
          index === 1 ||
          index === 2 ||
          index === 3 ||
          index === 4 ||
          index === 5 ||
          index === 6 ||
          index === 7 ||
          index === 8
        ) {
          return;
        }
        if (index === 9) {
          sums[index] += "元";
          return;
        }

        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += "元";
        }
      });

      return sums;
    },
    getSupplierID(val) {
      this.formInline.SupplierId = val;
    },
    //获取供货商列表
    GetAnySupplierList() {
      var self = this;
      var para = {
        sessionid: sessionStorage.getItem("sessionid")
      };
      para = {
        "": Base64.encode(JSON.stringify(para))
      };
      GetAnySupplierList(para).then(res => {
        //										console.log(JSON.parse(Base64.decode(res.data.Data)))
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          self.SupplierList = JSON.parse(Base64.decode(res.data.Data));
        }
      });
    },
    //获取商品列表
    getSkuList() {
      var self = this;
      var para = {
        sessionid: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        page: this.page,
        pagesize: this.pageSize,
      };
      this.skulistLoading = true;
      SKUList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取商品列表", vdata);
          var list = vdata.DataList;
          for (var item in list) {
            list[item].OrderNum = 1;
            list[item].Description = "";
          }
          self.skulist = list;
          self.total = vdata.TotalCount;
        }
        self.skulistLoading = false;
      });
    },
    addSubmit() {
      var self = this;
      if (!this.formInline.ordervoucher) {
        this.$message({
          message: "请输入采购单号",
          type: "error"
        });
        self.OderVisible = false;
        return;
      }

      if (!this.formInline.buyer) {
        this.$message({
          message: "请输入采购人",
          type: "error"
        });
        self.OderVisible = false;
        return;
      }

      if (!this.formInline.SupplierId) {
        this.$message({
          message: "请选择供货商",
          type: "error"
        });
        self.OderVisible = false;
        return;
      }
      if (!this.formInline.suppliermoblie) {
        this.$message({
          message: "请输入供货商电话号码",
          type: "error"
        });
        self.OderVisible = false;
        return;
      }

      var list = self.jsonspr;
      if (list.length < 1) {
        this.$message({
          message: "请选择订货商品",
          type: "error"
        });
        self.OderVisible = false;
        return;
      }
      for (var item in list) {
        if (!list[item].OrderNum || list[item].OrderNum <= 0) {
          this.$message({
            message: "订货数量不能为空",
            type: "error"
          });
          self.OderVisible = false;
          return;
        }
      }
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        ordervoucher: this.formInline.ordervoucher,
        SupplierId: this.formInline.SupplierId,
        //					OutDate: this.formInline.OutDate,
        buyer: this.formInline.buyer,
        suppliermoblie: this.formInline.suppliermoblie,
        jsonspr: this.jsonspr
      };
      // 先检查

      // 循环
      for (var item in this.jsonspr) {
        this.jsonspr[item].SupplierId = this.formInline.SupplierId;
      }
      console.log(para);
      PurchaseOrder(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          self.formInline.ordervoucher = "";
          self.formInline.SupplierId = "";
          self.formInline.buyer = "";
          self.formInline.suppliermoblie = "";
          self.getSkuList();
          this.$message({
            message: res.data.Description,
            type: "success"
          });
        }
      });

      self.OderVisible = false;
    },
    //显示历史列表界面
    handleHistory: function() {
      //				this.addFormVisible = true;
      //				this.addForm = {}
      this.$router.push({
        path: "/Oder/historylist"
      });
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    changeNum(row) {
      for (var item in this.jsonspr) {
        if (this.jsonspr[item].ProductId == row.ProductId) {
          this.jsonspr[item] = row;
        }
      }
    },
    handleSelectionChange(val) {
      console.log(val);
      this.jsonspr = val;
    },

    handleCurrentChange(val) {
      this.page = val;
      this.getSkuList();
    }
  }
};
</script>

<style>
</style>